local yaopan = fk.CreateSkill {
  name = "3s__yaopan",
}

local DIY = require "packages/diy_utility/diy_utility"
local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["3s__yaopan"] = "邀叛",
  [":3s__yaopan"] = "你失去过至少两张牌名相同的牌的回合结束时，你可以令至多等量名角色从本回合弃牌堆中各获得其中一张此牌名的牌，然后因此获得牌的角色依次选择：1.对你指定的一名角色使用一张【杀】（无距离限制）；2.弃置其手牌中所有此牌名的牌。",

  ["#lvshi__yaopan-get"] = "邀叛：选择获得的牌",
  ["#3s__yaopan-invoke"] = "邀叛：你可以令至多 %arg 名角色从弃牌堆获得【%arg2】",
  ["#3s__yaopan-slash"] = "邀叛：选择 %dest 使用【杀】的目标",
  ["#3s__yaopan-choice"] = "邀叛：选择对 %dest 使用【杀】，否则你弃置所有【%arg】",

  ["$3s__yaopan1"] = "",
  ["$3s__yaopan2"] = "",
}
yaopan:addAcquireEffect(function (self, player, is_start)
  player.room:addSkill("#CenterArea")
end)

yaopan:addEffect(fk.TurnEnd, {
  can_trigger = function(self, event, target, player, data)
    local room = player.room
    if player:hasSkill(yaopan.name) then
      -- 检查本回合失去的牌
      local lostCards = {}
      room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function (e)
        for _, move in ipairs(e.data) do
          if move.from == player then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                table.insertIfNeed(lostCards, info.cardId)
              end
            end
          end
        end
      end, Player.HistoryTurn)
      local card_name_count = {}
      for _, card_id in ipairs(lostCards) do
        local card = Fk:getCardById(card_id)
        if card then
          local card_name = card.trueName
          card_name_count[card_name] = (card_name_count[card_name] or 0) + 1
        end
      end
      -- 找到至少两张相同牌名的牌
      local valid_card_names = {}
      local max_count = 0
      for card_name, count in pairs(card_name_count) do
        if count >= 2 then
          table.insert(valid_card_names, card_name)
          if count > max_count then
            max_count = count
          end
        end
      end
      if #valid_card_names == 0 then return end
      if max_count > 1 then
        event:setCostData(self, {
          card_names = valid_card_names,
          card_count = max_count,
        })
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cost_data = event:getCostData(self)
    local card_names = cost_data.card_names
    local card_name = ""
    if #card_names > 1 then
      local listNames = card_names
      local listCards = {}
      for i = 1, #listNames do
        listCards[i] = {}
      end
      for _, id in ipairs(DIY.getCenterCards(room)) do
        local card = Fk:getCardById(id)
        if table.contains(card_names, card.trueName) then
          table.insertIfNeed(listCards[table.indexOf(listNames, card.trueName)], id)
        end
      end
      local choice = U.askForChooseCardList(room, player, listNames, listCards, 1, 1, yaopan.name,
        "#lvshi__yaopan-get", false, false)
      if #choice == 1 then
        card_name = choice[1]
      end
    else
      card_name = card_names[1]
    end
    local available_cards = table.filter(DIY.getCenterCards(room), function(id)
      return Fk:getCardById(id).trueName == card_name
    end)
    local n = math.min(cost_data.card_count, #available_cards)
    local to = room:askToChoosePlayers(player, {
      targets = room:getAlivePlayers(),
      min_num = 1,
      max_num = n,
      skill_name = yaopan.name,
      cancelable = false,
      prompt = "#3s__yaopan-invoke:::" .. n .. ":" .. card_name
    })
    -- 从弃牌堆分配牌（参考五谷丰登的选牌机制）
    local to_gain = table.simpleClone(available_cards)
    -- 为每个选中的角色依次选择获得牌
    for _, p in ipairs(to) do
      if #to_gain > 0 then
        -- 亮出可选的牌，让角色选择一张
        local chosen, _ = room:askToChooseCardsAndChoice(p, {
          cards = to_gain,
          skill_name = yaopan.name,
        })
        if chosen then
          room:obtainCard(p, chosen[1], true, fk.ReasonJustMove, p, yaopan.name)
          table.removeOne(to_gain, chosen[1])
        end
      end
    end
    -- 让获得牌的角色依次选择
    for _, gainer in ipairs(to) do
      if not gainer.dead then
        -- 选择使用杀的目标
        local to_use_slash = false
        local targets = room:getOtherPlayers(gainer)
        targets = table.filter(targets, function(p) return not p.dead end)
        local to_slash = room:askToChoosePlayers(player, {
          skill_name = yaopan.name,
          min_num = 1,
          max_num = 1,
          prompt = "#3s__yaopan-slash::" .. gainer.id,
          targets = targets,
        })
        if to_slash and #to_slash > 0 then
          -- 指定使用杀（无距离限制）
          local extra_data = {
            must_targets = {to_slash[1].id},
            bypass_times = true,
            bypass_distances = true,
          }
          local use = room:askToUseCard(gainer, {
            skill_name = yaopan.name,
            pattern = "slash",
            prompt = "#3s__yaopan-choice::" .. to_slash[1].id .. ":" .. card_name,
            cancelable = true,
            extra_data = extra_data,
          })
          if use then
            use.extraUse = true
            to_use_slash = true
            room:useCard(use)
          end
        end
        if not to_use_slash and gainer:isAlive() then
          -- 弃置所有此牌名的牌
          local to_discard = table.filter(gainer:getCardIds("h"), function(c) return Fk:getCardById(c).trueName == card_name end)
          if #to_discard > 0 then
            room:throwCard(to_discard, yaopan.name, gainer, gainer)
          end
        end
      end
    end
  end,
})

return yaopan